package cn.edu.scau.cmi.yejiancong.ORM_hibernate.DAO;

import java.util.List;
import java.util.Scanner;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.jupiter.api.Test;

import cn.edu.scau.cmi.yejiancong.ORM_hibernate.Utils.hibernateUtils;
import cn.edu.scau.cmi.yejiancong.ORM_hibernate.entiry.Student;
import cn.edu.scau.cmi.yejiancong.ORM_hibernate.entiry.Teacher;

public class teacherDAO {
	private static Session session=hibernateUtils.getSessionFactory().openSession();
	//crud
	
	
	
	@Test
	public static List<Teacher> getall(){
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			String hql="from Teacher";
			Query<Teacher> query=session.createQuery(hql);
			List<Teacher> list=query.list();
			
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();// TODO: handle exception
			return null;
		}
	}
	
	
	

	@Test
	public static void add(Teacher Teacher) {
		
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			session.save(Teacher);
			tx.commit();
			System.out.println("success");
		} catch (Exception e) {
			System.out.println("error");
			tx.rollback();
			// TODO: handle exception
		}
		
	}
	
	@Test
	public static Teacher get(Integer id) {
		Transaction tx=null;
		
		try {
			tx=session.beginTransaction();
			Teacher teacher =session.get(Teacher.class, id);
			tx.commit();
			return teacher;
		} catch (Exception e) {
			tx.rollback();
			return null;// TODO: handle exception
		}
	}
	
	@Test
	public static List<Object[]> getstudent(Integer id) {
		
		Transaction tx=null;
		
		try {
			tx=session.beginTransaction();
			String hql=" from Teacher t inner join t.students where t.id="+id;
			Query<Object[]> query=session.createQuery(hql);
			List<Object[]> list=query.list();
			
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();
			return null;// TODO: handle exception
		}
	}
	
	@Test
	public static void del(Integer id) {
		Transaction tx=null;
		
		try {
			tx=session.beginTransaction();
			session.delete(session.get(Student.class, id));
			tx.commit();
			System.out.println("succeed");
		} catch (Exception e) {
			tx.rollback();// TODO: handle exception
		}
	}
	
}
